<template>
    <div id="integralsummary" v-loading="pageLoading">
        <cardComponent>
            <template slot="cardBody">
                <!-- 搜索表单模块 -->
                <el-form
                    class="searchForm"
                    ref="searchForm"
                    :model="searchForm"
                    :rules="rules"
                    :inline="true"
                    label-position="right"
                    size="small"
                    label-width="100px"
                >
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="主卡卡号:" label-position="left" prop="mainCardNo">
                                <el-input v-model="cardInfo_3004.CARDNO" disabled></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="8">
                            <el-form-item label-position="left" prop="startDate" label="起始日期:">
                                <el-date-picker
                                    v-model="searchForm.startDate"
                                    type="date"
                                    placeholder="请选择起始日期"
                                    value-format="yyyyMMdd"
                                    format="yyyy-MM-dd"
                                    :picker-options="startOptions"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="buttonBox">
                        <el-col :span="8">
                            <el-form-item prop="endDate" label-position="left" label="结束日期:">
                                <el-date-picker
                                    v-model="searchForm.endDate"
                                    type="date"
                                    placeholder="请选择结束日期"
                                    value-format="yyyyMMdd"
                                    format="yyyy-MM-dd"
                                    :picker-options="endtOptions"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-radio
                                v-model="searchForm.selectDate"
                                @change="setDate"
                                label="1"
                                size="small"
                                border
                            >近3个月</el-radio>
                            <el-radio
                                v-model="searchForm.selectDate"
                                @change="setDate"
                                label="2"
                                size="small"
                                border
                            >近6个月</el-radio>
                            <el-radio
                                v-model="searchForm.selectDate"
                                @change="setDate"
                                label="3"
                                size="small"
                                border
                            >近12个月</el-radio>
                        </el-col>
                        <el-col :span="5">
                            <el-button
                                type="primary"
                                size="small"
                                icon="el-icon-search"
                                @click="handleGetListData()"
                            >查 询</el-button>
                            <el-button
                                type="primary"
                                size="small"
                                icon="el-icon-refresh-right"
                                @click="handleReset"
                            >重 置</el-button>
                        </el-col>
                    </el-row>
                </el-form>

                <div v-show="isShowTotal" class="box-card" style="padding: 20px;">
                    <h2 class="itme-header-left">银行积分</h2>
                    <el-row>
                        <el-col :span="12">
                            <div class="text item">
                                <div class="itme-text">银行积分总积分:</div>
                                <span>{{integralSummaryObj.PointTotal}}</span>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="text item">
                                <div class="itme-text">可兑换银行总积分:</div>
                                <span>{{integralSummaryObj.PtAvb01}}</span>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <div class="text item">
                                <div class="itme-text">即将到期积分:</div>
                                <span>{{integralSummaryObj.DuePoint}}</span>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="text item">
                                <div class="itme-text">即将到期日期:</div>
                                <span>{{integralSummaryObj.DueDate | formatDate}}</span>
                            </div>
                        </el-col>
                    </el-row>
                </div>

                <!-- 积分明细表格数据展示模块 -->
                <div v-show="isShowView">
                    <el-table
                        :data="tableData"
                        border
                        stripe
                        header-row-class-name="headerRow"
                        ref="showListTable"
                        class="heard-bg business_table"
                    >
                        <el-table-column label="积分日期">
                            <template
                                slot-scope="scope"
                            >{{scope.row.TranDate | getFormatTime(scope.row.Trantime)}}</template>
                        </el-table-column>

                        <el-table-column label="交易金额">
                            <template slot-scope="scope">{{scope.row.TransMoney}}</template>
                        </el-table-column>
                        <el-table-column label="积分值">
                            <template slot-scope="scope">{{scope.row.ExchangePoints}}</template>
                        </el-table-column>
                        <el-table-column label="交易描述">
                            <template slot-scope="scope">{{scope.row.TransDesc}}</template>
                        </el-table-column>
                        <el-table-column label="卡号后四位">
                            <template slot-scope="scope">{{scope.row.Trancardno | getFormatCard}}</template>
                        </el-table-column>
                        <el-table-column label="交易流水号">
                            <template slot-scope="scope">{{scope.row.TranSeq}}</template>
                        </el-table-column>
                    </el-table>
                    <div class="hstable_wrap" v-if="speechList.length!=0">
                        <el-table
                            :data="speechList"
                            border
                            stripe
                            header-row-class-name="headerRow"
                            ref="showListTable"
                            class="heard-bg business_table hstable"
                            @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                            <el-table-column label="业务话术">
                                <template slot-scope="scope">{{scope.row.content}}</template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="footer">
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('pre')"
                            :disabled="currentPageIndex <= 0"
                        >上一页</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleChangePage('next')"
                            :disabled="!nextButtonFlag"
                        >下一页</el-button>
                    </div>
                </div>
            </template>
        </cardComponent>
    </div>
</template>

<script>
// 积分汇总查询
import moment from 'moment';
import { mapState } from 'vuex';
import { getAccountTypeName, myMoment } from '@/utils/Common';
import cardComponent from '@/components/cardComponent/cardComponent.vue';

export default {

    name: 'IntegralSummaryChecked',
    components: {
        cardComponent,
    },
    data() {
        return {
            pageLoading: false, // 页面loading
            nextButtonFlag: false, // 下翻页按钮 显示控制阀
            ITEMCM: '',
            integralSummaryObj: {},//积分汇总信息
            integralStmtObj: {},//积分账单信息

            ACCOUNTTYPELIST: [], // 账户类型 下拉选择列表
            searchForm: { // 搜索表单字段
                selectDate: '',
                startDate: moment(new Date(new Date().getTime() - (1000 * 60 * 60 * 24 * 30))).format('YYYYMMDD'), // 开始日期 默认为当前日期往前一个月
                endDate: moment(new Date()).format('YYYYMMDD'), // 结束日期 默认为当前日期
            },
            rules: { // 表单校验规则
                startDate: [
                    { required: true, message: '请选择起始日期', trigger: 'blur' },
                ],
                endDate: [
                    { required: true, message: '请选择结束日期', trigger: 'blur' },
                ],
            },
            startOptions: { // 开始日期选择 限制
                disabledDate: (time) => {
                    if (this.searchForm.endDate) {
                        return time.getTime() > new Date(moment(this.searchForm.endDate).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },
            endtOptions: { // 结束日期选择限制
                disabledDate: (time) => {
                    if (this.searchForm.startDate) {
                        return time.getTime() < new Date(moment(this.searchForm.startDate).format('YYYY-MM-DD HH:mm:ss')).getTime();
                    }
                },
            },
            tableData: [],//积分明细列表信息
            currentSelectRow: '', //
            currentRowData: '', // 当前选择行的数据

            pagingDataList: [], // 翻页上送字段列表
            currentPageIndex: 0, // 当前页
            isShowTotal: false,
            isShowView: false,
            speechList: [],//话术列表
            selectedList: [],
        };
    },
    computed: mapState({
        cardInfo_3004: state => state.common.cardInfo_3004,
        cardList_3601: state => state.common.cardList_3601, // 卡列表数据
        defaultParams: state => state.common.defaultParams,
        defaultpinFlag: state => state.common.pinFlag,
        isCurrentMenuInfo: state => state.menu.isCurrentMenuInfo,
    }),
    filters: {
        // 日期格式转换
        formatDate(val) {
            let text = '';
            if (val) {
                if (typeof (val) === 'string') {
                    if (val.trim()) {
                        text = `${val.substring(0, 4)}-${val.substring(4, 6)}-${val.substring(6, 8)}`;
                    }
                } else {
                    const time = `${val}`;
                    text = `${time.substring(0, 4)}-${time.substring(4, 6)}-${time.substring(6, 8)}`;
                }
            }
            return text;
        },

        // 取卡号后四位
        getFormatCard(val) {
            let card4end = ''
            card4end = val.trim()
            card4end = card4end.substring(card4end.length - 4)
            return card4end
        },

        // 时间处理
        getFormatTime(date, time) {
            let res = '';
            if (date) {
                res = moment(`${date}`).format('YYYY-MM-DD');
            }
            if (time) {
                res = `${res} ${myMoment(time).format('HH:mm:ss')}`;
            }
            return res;
        },
    },
    async mounted() {
        //this.getData();
        // 获取账户类型
        this.ITEMCM = await getAccountTypeName(this.cardList_3601, this.cardInfo_3004, this);
        // 获取账户类型下拉列表
        // this.getAccountTypeData({ dictValue: 'CATE' }, 'ACCOUNTTYPELIST');
        await this.getspeechList();
    },
    methods: {
        // 获取账户类型列表
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            var checkParam = {
                'id': this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    } else {
                        const ErrorMessage = `错误码：${res.data.status} ` + `错误信息：${res.data.msg}`;
                        this.$alert(ErrorMessage, '请求异常:', {
                            customClass: 'error', type: 'error',
                        });
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },

        /**
         * 交易码：6901
         * 交易名称：积分汇总查询
         * 交易码：6912
         * 交易名称：积分账单查询
         */
        handleGetListData() {

            this.pageLoading = true; // 页面loading
            const appBody = {
                CARDNBR: this.cardInfo_3004.CARDNO || '', // 卡号
                OPERCODE: 0, // 操作代码  0全部返回  1未还款的贷款交易    2已还款的贷款交易
                PINFLAG: this.defaultpinFlag, // 是否检查密码标志
                PIN: '', // 密码
                INQOPT: 1, // 查询方式 （1按卡号查询 2按证件号查询）
                LEVEL: 1, // 查询级别 1、客户级 2、卡账户级 3、卡片级 （查询方式为1时，支持123，查询方式为2时只支持1）
                BEGDAY: '', // 起始日期
                ENDDAY: '', // 终止日期
                NEXTDAY: '',
                NEXTMPNO: 0,
            };
            this.defaultParams.sysHead.busiName = '积分汇总查询';
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams.body.appHead.tranCode = '6901';
            defaultParams.body.appBody = appBody;
            this.$post.common.transPort(defaultParams).then((res) => {

                this.pageLoading = false;
                if (res.status === 200) {
                    this.isShowTotal = true;
                    this.isShowView = true;
                    const result = JSON.parse(res.data.jsonRes);
                    if (result.sysHead.rspCd === '000000') {
                        this.integralSummaryObj = result.body.appBody;
                    }
                }

            });

            const appBody6912 = {
                CARDNBR: this.cardInfo_3004.CARDNO || '', // 卡号
                OPERCODE: 0, // 操作代码  0全部返回  1未还款的贷款交易    2已还款的贷款交易
                PINFLAG: this.defaultpinFlag, // 是否检查密码标志
                PIN: '', // 密码
                OPT: 1, // 查询方式 （1按卡号查询 2按证件号查询）
                LEVEL: 1, // 查询级别 1、客户级 2、卡账户级 3、卡片级 （查询方式为1时，支持123，查询方式为2时只支持1）
                FLAG: '0',
                TRANYM: '', // 
                RTNIND: '', // 
                PRIKEY: '',
                CUSTDATA: '',
                RESERVE: '',
            };
            this.defaultParams.sysHead.busiName = '积分汇总查询';
            const defaultParams6912 = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams6912.body.appHead.tranCode = '6912';
            defaultParams6912.body.appBody = appBody6912;
            this.$post.common.transPort(defaultParams6912).then((res) => {

                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    if (result.sysHead.rspCd === '000000') {
                        if (result.body.appBody.COUNTS > 0) {
                            this.integralStmtObj = result.body.appBody.dataList[0];
                        }
                    }
                }

            });

            this.handleGetDetailListData('first');
        },

        /**
                 * 交易码：6903
                 * 交易名称：积分明细查询
                 */
        handleGetDetailListData(type) {
            console.log("开始查询积分明细:" + type);
            this.tableData = [];
            let TranType = '';
            let TranDate = '';
            let Trantime = '';
            let TranSeq = '';
            let RTNID = '';
            if (type != 'first') {
                if (this.pagingDataList.length) { // 判断翻页上传字段取值
                    TranType = this.pagingDataList[this.currentPageIndex].TranType;
                    Trantime = this.pagingDataList[this.currentPageIndex].Trantime;
                    TranDate = this.pagingDataList[this.currentPageIndex].TranDate;
                    TranSeq = this.pagingDataList[this.currentPageIndex].TranSeq;
                    RTNID = this.pagingDataList[this.currentPageIndex].RTNID;
                }
            } else {
                this.pagingDataList = [];
            }


            const appBody6903 = {
                CARDNBR: this.cardInfo_3004.CARDNO || '', // 卡号
                OPERCODE: 0, // 操作代码  0全部返回  1未还款的贷款交易    2已还款的贷款交易
                PINFLAG: this.defaultpinFlag, // 是否检查密码标志
                PIN: '', // 密码
                OPT: 1, // 查询方式 （1按卡号查询 2按证件号查询）
                INQOPT: '1',    //查询方式，1、按起止日期，2、通过账单月
                LEVEL: 1, // 查询级别 1、客户级 2、卡账户级 3、卡片级 （查询方式为1时，支持123，查询方式为2时只支持1）
                STARTDATE: this.searchForm.startDate, // 起始日期
                PointPool: '01',//积分池，01-银行积分，02-商户积分，03-电子礼券
                ENDDATE: this.searchForm.endDate, // 终止日期
                RTNIND: this.pagingDataList.length === 0 ? '' : 1, // 翻页标志 首次传空， 翻页传1
                TranType,
                TranDate,
                Trantime,
                TranSeq,
                RTNID,
            };
            this.defaultParams.sysHead.busiName = '积分汇总查询';
            const defaultParams6903 = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams6903.body.appHead.tranCode = '6903';
            defaultParams6903.body.appBody = appBody6903;
            this.$post.common.transPort(defaultParams6903).then((res) => {

                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    console.log("积分汇总查询结果：", result);
                    if (result.sysHead.rspCd === '000000' && result.body.appBody.COUNTS != '0') {
                        this.tableData = result.body.appBody.dataList || [];

                        const currentPagingData = {
                            TranType: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].TranType,
                            TranDate: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].TranDate,
                            Trantime: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].Trantime,
                            TranSeq: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].TranSeq,
                            RTNID: result.body.appBody.dataList[result.body.appBody.dataList.length - 1].RTNID,
                        };
                        this.nextButtonFlag = !(result.body.appBody.RTNIND === '0');
                        let flag = false;
                        let currentIndex;
                        this.pagingDataList.forEach((item, index) => { // 判断此次查询数据最后一条记翻页分期付款序号是否在已有列表中
                            if (item.TranSeq === currentPagingData.TranSeq) {
                                flag = true;
                                currentIndex = index;
                            }
                        });
                        if (flag) { // 存在
                            this.currentPageIndex = currentIndex;
                        } else {
                            this.pagingDataList.push(currentPagingData);
                            this.currentPageIndex = this.pagingDataList.length - 1;
                        }
                    }
                }
            });

        },
        // 上下页切换
        handleChangePage(type) {
            // 翻页之前先清空 当前选择行数据
            this.currentRowData = '';
            if (type === 'pre') { // 切换到上一页
                if (this.currentPageIndex - 2 < 0) {
                    this.pagingDataList = []; // 清空缓存 申请编号 -> 相当于首次查询
                } else {
                    this.currentPageIndex = this.currentPageIndex - 2;
                }
                this.handleGetDetailListData(type);
            } else { // 切换到下一页
                this.handleGetDetailListData
                    (type);
            }
        },

        handleReset() {
            this.$refs.searchForm.resetFields();
            // 清空当前选择行数据
            this.currentRowData = '';
            // 清空缓存翻页数据
            this.pagingDataList = [];
            this.searchForm.selectDate = '';
            // this.handleGetListData()
        },
        setDate(val) {
            if (val === '1') {
                console.log("日期选项：" + val);
                this.searchForm.startDate = moment().add(-3, 'months').format('YYYYMMDD'); // 开始日期 默认为当前日期往前3个月
            } else if (val === '2') {
                console.log("日期选项：" + val);
                this.searchForm.startDate = moment().add(-6, 'months').format('YYYYMMDD'); // 开始日期 默认为当前日期往前6个月
            } else if (val === '3') {
                console.log("日期选项：" + val);
                this.searchForm.startDate = moment().add(-12, 'months').format('YYYYMMDD');  // 开始日期 默认为当前日期往前一年
            }
        }
    },
};
</script>

<style lang='scss'>
#integralsummary {
    .el-card .el-card__body,
    .el-card__header {
        padding: 10px;
    }
    .buttonBox {
        .el-col {
            .el-radio {
                margin-right: 10px;
            }
            .el-radio.is-bordered {
                padding: 9px 16px 0 10px;
                height: 36px;
            }
        }
    }
    .footer {
        text-align: center;
        margin-top: 30px;
    }
    .myCardComponent {
        -webkit-box-shadow: none;
        box-shadow: none !important;
    }
    .itme-header-left {
        font-size: 18px;
        margin-bottom: 20px;
        text-align: center;
    }
    .itme-header {
        font-weight: 400;
        color: #1f2f3d;
        text-align: left;
        margin-left: 15px;
    }
    .text {
        font-size: 14px;
    }
    .item {
        margin-bottom: 12px;
        color: #111;
        margin: 0 0 15px 15px;
    }
    .itme-text {
        display: inline-block;
        text-align: right;
        width: 50%;
        color: #666;
        margin-right: 15px;
    }
    .clearfix {
        // line-height: 30px;
        text-align: left;
        &:before,
        &:after {
            display: table;
            content: "";
        }
        &:after {
            clear: both;
        }
    }
    .box-card {
        width: 100%;
    }
    .searchForm {
        .el-form-item__content {
            display: inline-block;
        }
    }
}
</style>
